package tw.twandroidproj.app.ui.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.nostra13.universalimageloader.utils.L;
import com.orm.SugarRecord;

import java.util.List;

import tw.twandroidproj.app.R;
import tw.twandroidproj.app.model.Auth;
import tw.twandroidproj.app.model.ErrorModel;
import tw.twandroidproj.app.network.AuthManager;
import tw.twandroidproj.app.network.NetworkManager;
import tw.twandroidproj.app.network.OnResponseListener;

/**
 * Created by hasee on 2016/11/24.
 */

public class MessageActivity extends AppCompatActivity {

    private WebView msgweb;
    AuthManager msg_authmanager;
    String msg_url;
    @SuppressLint({ "JavascriptInterface", "SetJavaScriptEnabled" })
    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message);

        msg_authmanager=AuthManager.getInstance(this);
        setSupportActionBar((android.support.v7.widget.Toolbar) findViewById(R.id.toolbar_message));
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        msg_url="http://tjz.frezc.com/msg_center/index.html?token="+msg_authmanager.getToken()+"&id="+String.valueOf(msg_authmanager.getLoginUser().getUid());
        Log.v("token",msg_authmanager.getToken());
        Log.v("id",String.valueOf(msg_authmanager.getLoginUser().getUid()));
        Log.v("url",msg_url);
        msgweb= (WebView) findViewById(R.id.message_webview);
        msgweb.getSettings().setJavaScriptEnabled(true);

        msgweb.loadUrl(msg_url);



        msgweb.setWebViewClient(new msgwebview());

        msgweb.addJavascriptInterface(new nativeInterface(MessageActivity.this),"nativeInterface");


    }



    @Override
    //设置回退
    //覆盖Activity类的onKeyDown(int keyCoder,KeyEvent event)方法
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && msgweb.canGoBack()) {
            msgweb.goBack(); //goBack()表示返回WebView的上一页面
            return true;
        }

        return super.onKeyDown(keyCode,event);
    }

    //Web视图
    private class msgwebview extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }


    public class nativeInterface{
        Context context;
        public nativeInterface(Context c){
            this.context=c;
        }
        final List<Auth> msg_list= SugarRecord.listAll(Auth.class);
        /**
         * 和js交互用到的方法，js调用的
         */
        @JavascriptInterface
        public void toast(String msg){
            Toast.makeText(getBaseContext(),msg,Toast.LENGTH_SHORT).show();
        }

        @JavascriptInterface
        public void tokenExpired(){
            msg_authmanager.refresh(msg_list.get(0).getToken(), new OnResponseListener<String>() {
                @Override
                public void onSuccess(String result) {
                     msgweb.reload();
                }

                @Override
                public void onFailed(ErrorModel errorModel) {
                    if(errorModel.getStatus_code()==-1){
                        Toast.makeText(getBaseContext(), "请检查网络连接", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
        @JavascriptInterface
        public void tokenInvalid(){

                msg_authmanager.logout();
                startActivity(new Intent(MessageActivity.this,LoginActivity.class));
                finish();
                Toast.makeText(getBaseContext(), "登录失效，请重新登录", Toast.LENGTH_SHORT).show();
        }
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();


        if(id==android.R.id.home){
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    }
